import cv2
import numpy as np

img = cv2.imread("./img/words.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)

# 图形处理中,膨胀和腐蚀
kernel = np.array([
    [1., 1., 1., 1., 1.],
    [1., 1., 1., 1., 1.],
    [1., 1., 1., 1., 1.],
    [1., 1., 1., 1., 1.],
    [1., 1., 1., 1., 1.]
])
# 膨胀
cv2.imshow("binary1", binary)
binary = cv2.dilate(binary, kernel)
binary = cv2.dilate(binary, kernel)
cv2.imshow("binary2", binary)
# 腐蚀 :(消除图像中游离或者零散的白色点.)
# binary = cv2.erode(binary,kernel)

contours,ret = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=1)
cv2.imshow("img", img)
cv2.waitKey(0)
